/**
 *     Copyright (C) 2009 Anders Aagaard <aagaande@gmail.com>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.neuron.BacklightOff;

import java.io.DataOutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class BacklightOff extends Activity {
	public static final String KEY_BACKLIGHTOFF = "backlightoff";
	public static final String KEY_RUN_ON_BOOT = "runOnBoot";
    /** Called when the activity is first created. */
	private static final String TAG = "BacklightOff";

	
	// UI elements:
	private ToggleButton toggle_state_btn;
	private ToggleButton toggle_state_onboot_btn;
	private Button testroot_btn;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
		final SharedPreferences preferences = getSharedPreferences("backlightoff", MODE_PRIVATE);
		Boolean pref_backlightoff = preferences.getBoolean(KEY_BACKLIGHTOFF, false);
		Boolean pref_runOnBoot = preferences.getBoolean(KEY_RUN_ON_BOOT, true);
		
        testroot_btn = (Button) findViewById(R.id.testroot_btn);
        testroot_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean rootOk = testRoot();
				TextView toggle_state_label = (TextView) findViewById(R.id.toggle_state_label);
				if (rootOk) {
					toggle_state_label.setText("Root access is : OK");
				} else {
					toggle_state_label.setText("Root access is : Not working!");
					TextView roothelp_text = (TextView) findViewById(R.id.roothelp_text);
					//roothelp_text.setVisibility(View.VISIBLE);
					roothelp_text.setText("To get root, google your device name + root and start reading. For example g1 root.\nNote that rooting a device is unsupported, and I can not help in root related questions.");
				}
			}
        });


        toggle_state_btn = (ToggleButton) findViewById(R.id.toggle_state_btn);
        toggle_state_btn.setChecked(pref_backlightoff);
        toggle_state_btn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (!setBacklightOff(BacklightOff.this, isChecked)) {
					toggle_state_btn.setChecked(false);
				}
			}
        });
        
        toggle_state_onboot_btn = (ToggleButton) findViewById(R.id.toggle_state_onboot_btn);
        toggle_state_onboot_btn.setChecked(pref_runOnBoot);
        toggle_state_onboot_btn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				SharedPreferences.Editor editor = getSharedPreferences("backlightoff", MODE_PRIVATE).edit();
		    	editor.putBoolean(KEY_RUN_ON_BOOT, isChecked);
				editor.commit();
			}
        });
        
    }
    
    private boolean testRoot() {
    	try {
    		Process process = Runtime.getRuntime().exec("su -c echo");
    		//DataOutputStream os = new DataOutputStream(process.getOutputStream());
    		if (process.waitFor() != 0)
    			return false;
    	} catch (Exception e) {
    		Log.e(TAG, "Exception getting root status", e);
    		return false;
    	}
		return true;
    }
    
    static public void setPreferancesState(Context c, Boolean state) {
		SharedPreferences.Editor editor = c.getSharedPreferences("backlightoff", MODE_PRIVATE).edit();
    	editor.putBoolean(KEY_BACKLIGHTOFF, state);
		editor.commit();
    }
    
    static public void toggleBacklightOff(Context context) {
		final SharedPreferences preferences = context.getSharedPreferences("backlightoff", Activity.MODE_PRIVATE);
		Boolean pref_status = preferences.getBoolean(BacklightOff.KEY_BACKLIGHTOFF, false);
		BacklightOff.setBacklightOff(context, !pref_status);
    }

	static boolean setBacklightOff(Context c, boolean enabled) {
		Log.i(TAG, "Trying to change backlight status to " + enabled);
		try
		{
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream os = new DataOutputStream(process.getOutputStream());
			if (enabled) {
				/*
				 * Disable backlight and set brightness file to read only.
				 */
				Toast.makeText(c, "Setting backlight status to : Forced off", Toast.LENGTH_SHORT).show();
				os.writeBytes("echo 0 > /sys/class/leds/keyboard-backlight/brightness\n" +
							"chmod 444 /sys/class/leds/keyboard-backlight/brightness\n");
				os.flush();
				setPreferancesState(c, enabled);
				return true;
			} else {
				/*
				 * Enable backlight, enable write to brightness file, and if keyboard visible enable backlight.
				 */
				Toast.makeText(c, "Setting backlight status to : System controlled", Toast.LENGTH_SHORT).show();
				os.writeBytes("chmod 644 /sys/class/leds/keyboard-backlight/brightness\n");
				Configuration config = c.getResources().getConfiguration();
				if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
					os.writeBytes("echo 48 > /sys/class/leds/keyboard-backlight/brightness\n");
				}
				os.flush();
				setPreferancesState(c, enabled);
				return true;
			}
		} catch (Exception e)
		{
			Log.e(TAG, "Exception changing backlight", e);
			Toast.makeText(c,  "Exception changing backlight\n" + e, Toast.LENGTH_LONG).show();
			return false;
		}
    }
}